#include "enemy.h"
#include <QDebug>
#include <QGraphicsScene>  // 添加这一行

enemy::enemy(QPoint pos,const QString& spriteSheetPath,int frameWidth,int frameHeight,int framenumber, int animationSpeed)
             : currentframe(0),framewidth(frameWidth),frameheight(frameHeight),framenum(framenumber), enemymovespeed(7)

{
    // 加载精灵图
    if (!spritesheet.load(spriteSheetPath)) {
        qWarning() << "Failed to load sprite sheet:" << spriteSheetPath;
        return;
    }

    // 设置初始位置和尺寸
    setPos(pos);
    setPixmap(spritesheet.copy(0, 0,framewidth,frameheight));

    // 动画更新定时器
    animationtimer = new QTimer(this);
    connect(animationtimer, &QTimer::timeout, this, &enemy::updateFrame);
   animationtimer->start(30);

    // 移动定时器
   enemymovetimer = new QTimer(this);
    connect( enemymovetimer, &QTimer::timeout, this, &enemy::move);
     enemymovetimer->start(30);
    }



void enemy::updateFrame()
{
    // 计算当前帧在精灵图中的位置
    int x = (currentframe % framenum) * framewidth;
    int y = 0;
    // 更新显示帧
    setPixmap(spritesheet.copy(x, y, framewidth, frameheight));

    // 循环帧数
    currentframe = (currentframe + 1) % framenum;
}

void enemy::move()
{

    if (!scene()) {
        return;
    }
    // 向左移动
    setX(x() - enemymovespeed);

    // 移出屏幕后自动删除
   if (x() + pixmap().width() < 0) {
        emit destroyed(this); // 发送销毁信号
        scene()->removeItem(this);
        deleteLater();
    }
}
enemy::~enemy()
{
    if (animationtimer) {
        animationtimer->stop();
        delete animationtimer;
        animationtimer = nullptr;
    }
    if (enemymovetimer) {
        enemymovetimer->stop();
        delete enemymovetimer;
        enemymovetimer = nullptr;
    }
}
